package com.hxwm.hwdbtool.controller.dialog;

import com.hxwm.hwdbtool.core.DatabaseConnectionListener;
import com.hxwm.hwdbtool.entity.dbconnect.HwDateSource;
import com.hxwm.hwdbtool.util.JavaFXUIControlUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: hwdbtool
 * @ClassName MainMenuDBConnDialog
 * @description:
 * @author: hxwm
 * @create: 2024-05-09 22:42
 * @Version 1.0
 **/
public class MenuDBConnectDialog {
    Logger logger = Logger.getLogger(MenuDBConnectDialog.class);
    @FXML
    private DialogPane mainAppDBConnectDialog;
    @FXML
    private ListView<String> dbTypeListView;
    @FXML
    private FlowPane dbDriverFlowPane;
    @FXML
    private TextArea dbInfoTextArea;
    @FXML
    private TextField dbTypeTextField;
    @FXML
    private TextField dbPortTextField;
    @FXML
    private TextField dbIpTextField;
    @FXML
    private TextField dbNameTextField;
    @FXML
    private TextField dbUserTextField;
    @FXML
    private PasswordField dbPasswordField;
    @FXML
    private HBox dbTypeHBox;
    @FXML
    private HBox dbInfoHBox;
    @FXML
    private Button dbConnTestBtn;
    @FXML
    private Button backBtn;
    @FXML
    private Button nextBtn;
    @FXML
    private Button confirmBtn;
    @FXML
    private Button cancelBtn;
    @FXML
    private Button recognitionBtn;

    private String dbType;
    private DatabaseConnectionListener dbConnectListener;

    public DatabaseConnectionListener getDbConnectListener() {
        return dbConnectListener;
    }

    public void setDbConnectListener(DatabaseConnectionListener dbConnectListener) {
        this.dbConnectListener = dbConnectListener;
    }

    private static Map<String,String> driverSQL = new HashMap<>();
    private static Map<String,String> driverNoSQL = new HashMap<>();
    static {
        driverSQL.put("MySQL","/static/icon/driver/mysql.png");
        driverSQL.put("DB2","/static/icon/driver/DB2.png");
        driverSQL.put("Oracle","/static/icon/driver/Oracle.png");
        driverSQL.put("Informix","/static/icon/driver/Informix.png");
        driverSQL.put("SQLServer","/static/icon/driver/sqlserver.png");
        driverSQL.put("PostgreSQL","/static/icon/driver/postgresql.png");
        driverSQL.put("SQLite","/static/icon/driver/Sqlite.png");
        driverSQL.put("TiDB","/static/icon/driver/tidb.png");

        driverNoSQL.put("Redis", "/static/icon/dbtoolbar/old/db-new-conn.png");
    }

    public void initialize() {

        // 初始化操作，可以在这里添加事件监听器等
        ObservableList<String> databaseTypes = FXCollections.observableArrayList("SQL", "NoSQL");
        dbTypeListView.setItems(databaseTypes);

        dbDriverFlowPane.setHgap(10);
        dbDriverFlowPane.setVgap(10);

        //点击左侧选项事件
        dbTypeListView.setOnMouseClicked(e->{
            String selectedType = dbTypeListView.getSelectionModel().getSelectedItem();
            // 从dbDriverPane中移除按钮
            dbDriverFlowPane.getChildren().clear();

            Map<String,String> driverMap = new HashMap();
            if ("SQL".equals(selectedType)) {
                driverMap = driverSQL;
            } else if ("NoSQL".equals(selectedType)) {
                // 显示NoSQL相关按钮
                driverMap = driverNoSQL;
            }
            int col = 0;
            for(Map.Entry<String,String> entry : driverMap.entrySet()){
                Button button = new Button();
                button.setPrefSize(50, 50); // 设置按钮大小
                Image image = new Image(getClass().getResourceAsStream(entry.getValue()));
                ImageView imageView = new ImageView(image);
                imageView.setFitWidth(50);
                imageView.setFitHeight(50);
                button.setGraphic(imageView);
                dbDriverFlowPane.getChildren().add(button); // 添加按钮到GridPane
                if(col != 3){
                    col ++;
                }else{
                    col = 0;
                }
                button.setOnAction(event->{
                    dbTypeTextField.setText(entry.getKey());
                    nextBtn.setDisable(false);
                });
            }
        });
        dbConnTestBtn.setOnAction(e->{
            handleTestConnBtn();
        });
        backBtn.setOnAction(e->{
            handleBackBtn();
        });
        nextBtn.setOnAction(e->{
            handleNextBtn();
        });
        confirmBtn.setOnAction(e->{
            handleConfirmBtn();
        });
        cancelBtn.setOnAction(e->{
            handleCancelBtn();
        });
        recognitionBtn.setOnAction(e->{
            handleRecognition();
        });

    }
    private void handleTestConnBtn(){
        String dbTYpe = dbTypeTextField.getText();
        String dbName = dbNameTextField.getText();
        String dbUser = dbUserTextField.getText();
        String dbIp = dbIpTextField.getText();
        String dbPort = dbPortTextField.getText();
        String dbPassword = dbPasswordField.getText();
        //jdbc:mysql://localhost:3306/hwdemo
        String dbUrl = "jdbc:" + dbTYpe + "://" + dbIp + ":" + dbPort + "/" + dbName;
        JavaFXUIControlUtil.testDatabaseConnection(dbUrl, dbUser, dbPassword);
    }

    private void handleBackBtn(){
        dbTypeHBox.setVisible(true);
        dbInfoHBox.setVisible(false);
        dbConnTestBtn.setDisable(true);
        backBtn.setDisable(true);
        confirmBtn.setDisable(true);
        nextBtn.setDisable(false);
    }

    private void handleNextBtn(){
        dbTypeHBox.setVisible(false);
        dbInfoHBox.setVisible(true);
        dbConnTestBtn.setDisable(false);
        backBtn.setDisable(false);
        confirmBtn.setDisable(false);
        nextBtn.setDisable(true);
    }

    private void handleConfirmBtn(){
        switch (dbTypeTextField.getText()){
            case "MySQL":
                dbType = "mysql";
                break;
            case "DB2":
                dbType = "db2";
                break;
            case "Oracle":
                dbType = "oracle";
                break;
            case "Informix":
                dbType = "informix-sqli";
                break;
            default:
                break;
        }
        HwDateSource dateSource = new HwDateSource(dbType,dbIpTextField.getText(),dbPortTextField.getText(),dbNameTextField.getText(),dbUserTextField.getText(),dbPasswordField.getText());
        if(dbConnectListener != null){
            if(JavaFXUIControlUtil.testDatabaseConnection(dateSource)){
                dbConnectListener.onDatabaseConnected(dateSource);
            }else{
                JavaFXUIControlUtil.showInformationDialog("错误","添加数据源失败，连接失败");
            }
        }
        ((Stage)mainAppDBConnectDialog.getScene().getWindow()).close();
    }

    private void handleCancelBtn(){
        mainAppDBConnectDialog.getScene().getWindow().hide();
    }

    private void handleRecognition(){
        String dbInfo = dbInfoTextArea.getText();
        String[] dbInfoArray = dbInfo.split("\\n");//使用换行分割
        if(dbInfoArray != null && dbInfoArray.length < 3){
            dbInfoArray = dbInfo.split("\\s+");//使用空格分割
        }
        if(dbInfoArray != null && dbInfoArray.length >= 3){
            String dbUrl = dbInfoArray[0];
            String[] dbUrlArray = dbUrl.split("[:/]+");
            int length = dbUrlArray.length;

            if(length >= 3){
                dbIpTextField.setText(dbUrlArray[2]);
            }
            if(length >= 4){
                dbPortTextField.setText(dbUrlArray[3]);
            }
            if(length >= 5){
                dbNameTextField.setText(dbUrlArray[4]);
            }

            dbUserTextField.setText(dbInfoArray[1]);
            dbPasswordField.setText(dbInfoArray[2]);
        }
    }
}